/*
 * For com.royal.art
 * Copyright [2015/11/7] By RICK
 */
package com.manage.controller;

import com.beans.*;
import com.beans.page.PageList;
import com.commons.util.Constants;
import com.commons.util.CookieUtils;
import com.commons.util.StringUtil;
import com.manage.common.security.shiro.session.SessionDAO;
import com.manage.context.GlobalContext;
import com.manage.security.SystemAuthorizingRealm.Principal;
import com.manage.util.UserUtils;
import com.manage.util.Utils;
import com.services.*;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

/**
 * IndexController
 * index Controller
 *
 * @author FCHEN
 * @date 2015/11/7
 */
@Controller
@RequestMapping("/")
public class IndexController extends BaseController {

    @Autowired
    private SessionDAO sessionDAO;
    @Autowired
    private NewsContentService newsContentService;
    @Autowired
    private SubscribeService subscribeService;
    @Autowired
    private OwnerEntrustmentService ownerEntrustmentService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private FollowRecordService followRecordService;

    @RequiresPermissions("user")
    @RequestMapping(value = {"", "/", "index"})
    public String index(HttpServletRequest request, HttpServletResponse response) {
        Principal principal = UserUtils.getPrincipal();

        // 登录成功后，验证码计算器清零
        Utils.isValidateCodeLogin(principal.getLoginName(), false, true);

        if (logger.isDebugEnabled()) {
            logger.debug("show index, active session size: {}", sessionDAO.getActiveSessions(false).size());
        }

        // 如果已登录，再次访问主页，则退出原账号。
        if (GlobalContext.TRUE.equals(GlobalContext.getProperties("notAllowRefreshIndex"))) {
            String logined = CookieUtils.getCookie(request, "LOGINED");
            if (StringUtils.isBlank(logined) || "false".equals(logined)) {
                CookieUtils.setCookie(response, "LOGINED", "true");
            } else if (StringUtils.equals(logined, "true")) {
                UserUtils.getSubject().logout();
                return "redirect:" + adminPath + "/login";
            }
        }

        List<NewsContent> newsContentList = newsContentService.queryListByIndex();

        request.setAttribute("newsContentList", newsContentList);

        return "index";
    }

    /**
     * 异步获取list资源(抢单)
     *
     * @param pageList
     * @param subscribe
     * @return
     */
    @RequiresPermissions("newsContent:view")
    @RequestMapping("subscribe/asynList")
    @ResponseBody
    public PageList asynList(PageList pageList, Subscribe subscribe) {
        return subscribeService.queryPage(pageList, subscribe);
    }

    /**
     * 异步获取list资源(抢单)
     *
     * @param pageList
     * @param ownerEntrustment
     * @return
     */
    @RequiresPermissions("newsContent:view")
    @RequestMapping("ownerEntrustment/asynList")
    @ResponseBody
    public PageList asynList(PageList pageList, OwnerEntrustment ownerEntrustment) {
        return ownerEntrustmentService.queryPage(pageList, ownerEntrustment);
    }

    @RequiresPermissions("index:subscribe")
    @RequestMapping("subscribe")
    @ResponseBody
    public Object subscribe(Long subscribeId) {
        Subscribe subscribe = new Subscribe();
        subscribe.setSubscribeId(subscribeId);

        Subscribe s = subscribeService.queryById(subscribeId);//查询预订单,拿到客户电话

        if(!StringUtil.isEmpty(s)){
            Customer customer = new Customer();
            customer.setCreateBy(UserUtils.getUser().getUserId());
            customer.setCustomerPhone(s.getCustomerPhone());
            List<Customer> customers = customerService.queryList(customer);//用预约单的客户电话,查询该客户是否存在
            if(customers.size() < 1){
                //如果不存在,则创建要给客户
                customer.setStaus(1);
                customer.setCustomerName(s.getCustomerName());

                customer.setCreateBy(UserUtils.getUser().getUserId());
                customer.setUpdateBy(UserUtils.getUser().getUserId());

                customerService.add(customer);
            }else {
                customer = customers.get(0);
            }
            //添加房源带看记录
            FollowRecord followRecord = new FollowRecord();

            followRecord.setCreateBy(UserUtils.getUser().getUserId());
            followRecord.setUpdateBy(UserUtils.getUser().getUserId());
            followRecord.setUpdateDate(new Timestamp(new Date().getTime()));
            followRecord.setRelationId(customer.getCustomerId());
            followRecord.setRelationType(Constants.twoLong);//房源
            followRecord.setUserName(UserUtils.getUser().getdName());
            followRecord.setText("客户"+s.getCustomerName()+"预约的"+"房源编号为:"+s.getHouseId()+"的房子的订单,被"+UserUtils.getUser().getUsername()+"抢到,联系电话："+s.getCustomerPhone());

            followRecordService.add(followRecord);
        }

        int result = subscribeService.update(subscribe);

        //TODO  成功失败结果页面
        return result;
    }

    @RequiresPermissions("index:owner")
    @RequestMapping("owner")
    @ResponseBody
    public Object owner(Long contractId) {
        OwnerEntrustment ownerEntrustment = new OwnerEntrustment();
        ownerEntrustment.setContractId(contractId);

        OwnerEntrustment s = ownerEntrustmentService.queryById(contractId);//查询预订单,拿到客户电话

        if(!StringUtil.isEmpty(s)){
            Customer customer = new Customer();
            customer.setCreateBy(UserUtils.getUser().getUserId());
            customer.setCustomerPhone(s.getCustomerPhone());
            List<Customer> customers = customerService.queryList(customer);//用预约单的客户电话,查询该客户是否存在
            if(customers.size() < 1){
                //如果不存在,则创建要给客户
                customer.setStaus(1);
                customer.setCustomerName(s.getCustomerName());

                customer.setCreateBy(UserUtils.getUser().getUserId());
                customer.setUpdateBy(UserUtils.getUser().getUserId());

                customerService.add(customer);
            }else {
                customer = customers.get(0);
            }
            //添加房源带看记录
            FollowRecord followRecord = new FollowRecord();

            followRecord.setCreateBy(UserUtils.getUser().getUserId());
            followRecord.setUpdateBy(UserUtils.getUser().getUserId());
            followRecord.setUpdateDate(new Timestamp(new Date().getTime()));
            followRecord.setRelationId(customer.getCustomerId());
            followRecord.setRelationType(Constants.twoLong);//房源
            followRecord.setUserName(UserUtils.getUser().getdName());
            followRecord.setText("客户"+s.getCustomerName()+"委托的"+"房源为:"+s.getNbhName()+s.getBuildingNo()
                    +s.getUnitNo()+s.getRoomNo()+"的房子的订单,被"+UserUtils.getUser().getUsername()+"抢到,联系电话："+ownerEntrustment.getCustomerPhone());

            followRecordService.add(followRecord);
        }

        int result = ownerEntrustmentService.update(ownerEntrustment);

        //TODO  成功失败结果页面
        return result;
    }
}
